package com.ays.mesbackbone.common.distributed.id;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * <p>Title： NetworkSnowflakeIdGenerator </p>
 * <p>Description： </p>
 *
 * @author sujunxuan
 * @version V1.0
 * @date 2020/8/4 10:02
 */

@Component
@Primary
public class NetworkSnowflakeIdGenerator implements DistributedIdGenerator {

    private final SnowflakeWorker snowflakeWorker;

    public NetworkSnowflakeIdGenerator() {
        snowflakeWorker = new SnowflakeWorker(getDataCenterId(), getMachineId());
    }

    @Override
    public long generatorId() {
        return snowflakeWorker.nextId();
    }

    private long getMachineId() {
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            String[] split = hostAddress.split("\\.");
            return Long.parseLong(split[split.length - 1]);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, SnowflakeWorker.MAX_MACHINE_NUM);
        }
    }

    private long getDataCenterId() {
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            String[] split = hostAddress.split("\\.");
            long num = Long.parseLong(split[split.length - 2]);
            return num % (SnowflakeWorker.MAX_DATACENTER_NUM + 1);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, SnowflakeWorker.MAX_DATACENTER_NUM);
        }
    }
}

